package cc.cary.warehouse.common;

import lombok.Data;
import lombok.experimental.Accessors;

/**
 * REST API 返回结果
 *
 * @author Cary
 * @date 2023/4/18
 */
@Data
@Accessors(chain = true)
public class R<T> {
    /**
     * 业务错误码
     */
    private long code;
    /**
     * 结果集
     */
    private T data;
    /**
     * 描述
     */
    private String msg;

    public R() {
        // to do nothing
    }

    public R(int errorCode) {
        this.code = errorCode;
        this.msg = ErrorMessages.getErrorMessage(errorCode);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, ErrorConstants.SUCCESS, ErrorMessages.getErrorMessage(ErrorConstants.SUCCESS));
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, ErrorConstants.BUSINESS_ERROR, msg);
    }

    public static <T> R<T> failed(Integer errorCode) {
        return restResult(null, errorCode, ErrorMessages.getErrorMessage(errorCode));
    }

    private static <T> R<T> restResult(T data, long code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public boolean ok() {
        return ErrorConstants.SUCCESS == code;
    }
}
